package edu.yuhf.web.action;

import java.io.IOException;
import java.io.PrintWriter;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import edu.yuhf.entity.User;
import edu.yuhf.service.iface.UserService;



@Controller()
@Scope("prototype")
@Results({
	@Result(name="loginOk",location="/views/main.jsp"),
	@Result(name="error",location="/login.jsp"),
	@Result(name="registerOk",location="/login.jsp"),
	@Result(name="success",location="/register.jsp")
})
public class LoginAndRegistAction {

	private String userName;
	private String password;	
	private String telephone;
	private String message;
	
	@Resource
	UserService userService;	//从应用程序上下文中将一个已经实例化好的对象（userService），注入到当前的引用变量中。
	
	@Action(value="login")
	public String userLogin(){
		String result="error";
		System.out.println(userName+","+password);
		if(userService.userInfoCheck(userName, password)){
			result="loginOk";
		}
		return result;
	}
	
	@Action(value="register")
	public String register(){
		return "success";
	}
	
	@Action(value="doRegister")
	public String doRegister() throws IOException{
		String url="registerOk";
		message="register error";
		System.out.println(userName+","+password+","+telephone);
		User user=new User(userName,password,telephone);
		User user0=userService.insertUser(user);
		HttpServletResponse response=ServletActionContext.getResponse();
		response.setCharacterEncoding("utf-8");
		response.setContentType("text/html; charset=utf-8");
		PrintWriter out=response.getWriter();
		if(user0.getId()!=0){
			out.println("<script>alert('注册成功');window.location.href='login.jsp'</script>");
		}else{
			out.println("<script>alert('注册成功');window.location.href='login.jsp'</script>");
		}
		return null;
	}

	

	public UserService getUserService() {
		return userService;
	}
	public void setUserService(UserService userService) {
		this.userService = userService;
	}
	public String getUserName() {
		return userName;
	}
	public void setUserName(String userName) {
		this.userName = userName;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}

	public String getTelephone() {
		return telephone;
	}

	public void setTelephone(String telephone) {
		this.telephone = telephone;
	}

	public String getMessage() {
		return message;
	}

	public void setMessage(String message) {
		this.message = message;
	}
	
}
